package com.bparser.parser;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

public abstract class Utils {

	public static HttpURLConnection getConnectionFromString(String URL)
			throws IOException {
		URL url = new URL(URL);
		return (HttpURLConnection) url.openConnection();
	}

	public static String getStringFromStream(InputStream is) {
		BufferedReader br;
		String line, source = "";
		try {
			br = new BufferedReader(new InputStreamReader(is));
			while ((line = br.readLine()) != null) {
				source += line + "\n";
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return source;
	}

	public static Element getFirstElementFromString(String htmlSource,
			String cssQuery) {
		return getElementFromString(htmlSource, cssQuery, 0);
	}

	public static Element getElementFromString(String htmlSource,
			String cssQuery, int index) {
		Document doc = Jsoup.parse(htmlSource);
		return doc.select(cssQuery).get(index);
	}

	public static Elements getAllElementFromString(String htmlSource,
			String cssQuery) {
		Document doc = Jsoup.parse(htmlSource);
		return doc.select(cssQuery);
	}
}